$(function(){
	window.ajaxload_loading = $('.show-loading');

	// Remove link-to-no-where href
	$('a[href="##"]').attr('href', 'javascript:void(0)');

	// Must confirm
    $('.must-confirm').live('click', function(e){
    	var t = $(this);
        msg = t.attr('data-must-confirm-msg');
        msg = msg || 'Are you sure want to continue?';
        if(!confirm(msg)) {
            e.preventDefault();
            return false;
        }
        return true;
    });

	// Format datepicker
	$('.datepicker').addClass('input-small')
					.datepicker({
						dateFormat : 'yy/mm/dd',
						changeMonth: true,
						changeYear : true,
						yearRange  : '-90:+10'
					})
					.wrap('<div class="input-append"/>')
					.after('<span class="add-on"><i class="icon-calendar"></i></span>');

	// Ajax Load select
    $('.chainselect').live('change', function(){
        t  = $(this);//.attr('disabled', 'disabled');// commented-out
        tg = $(t.attr('data-chainselect-target')).html('<option>Loading ..</option>');
        $.ajax(t.attr('data-chainselect-source'), {
                data: {p:t.val()},
                dataType: 'json',
                success: function(d) {
                    t.removeAttr('disabled');
                    tg.html(renderSelectbox(d));
                },
                error:function(e){console.log(e);}
               });
    });

	// AJAX
	$('.ajax-placeholder').each(function(i, e){
		t = $(this);
		t.html('<div class="show-loading"><img src="/static/images/loading.gif"/></div>');
		src = t.attr('data-ajax-placeholder-src');
		$.ajax(src, {
			success: function(r) {
				t.html(r);
			}
		})
	});
	/**
	 * data-ajax-Link
	 *     . data-ajax-to
	 *     . data-ajax-elem
	 *     . data-ajax-dataType
	 *     . data-ajax-fn-pre
	 *     . data-ajax-fn-post
	 */
	$('a.ajax-link').live('click', function(e){
		e.preventDefault();
		
		var t = $(this), el = $(t.attr('data-ajax-elem'));
    	if(el) {
    		var dt, prp, pop;
    		dt  = t.attr('data-ajax-dataType') || 'html';
    		if(prp = t.attr('data-ajax-fn-pre')) {prp(el);}
    		pop = t.attr('data-ajax-fn-post');
    		ps  = (ps = t.attr('data-ajax-parser')) && eval(ps) || null;
    		
    		el.css({opacity:0.5});
    		ajaxload_loading.show();
    		
    		$.ajax(t.attr('data-ajax-to') || t.attr('href'), {
    			dataType: dt,
    			success : function(r) {
    				if(ps) {r = ps(r);}
    				el.html(r);
    				if(pop){pop(el,r);}
    				el.css({opacity:1});
    				ajaxload_loading.hide();
    			}
    		});
        }
	});
	
	$('a.ajax-link-must-confirm').live('click', function(e){
		e.preventDefault();
		
		var t = $(this), el = $(t.attr('data-ajax-elem'));
		
		msg = t.attr('data-must-confirm-msg');
		msg = 'Are you sure want to continue ?';
		if(!confirm(msg)) {
			e.preventDefault();
			return false;
		} else {
			if(el) {
				var dt, prp, pop;
				dt  = t.attr('data-ajax-dataType') || 'html';
				if(prp = t.attr('data-ajax-fn-pre')) {prp(el);}
				pop = t.attr('data-ajax-fn-post');
				ps  = (ps = t.attr('data-ajax-parser')) && eval(ps) || null;
				
				el.css({opacity:0.5});
				ajaxload_loading.show();
				
				$.ajax(t.attr('data-ajax-to') || t.attr('href'), {
					dataType: dt,
					success : function(r) {
						if(ps) {r = ps(r);}
						el.html(r);
						if(pop){pop(el,r);}
						el.css({opacity:1});
						ajaxload_loading.hide();
						// Set Value for a tags apter ajax -- MinhNT
						if(t.hasClass('label-success'))	{
							t.removeClass('label-success');
							t.addClass('label-warning');
						} else if (t.hasClass('label-warning')) {
							t.removeClass('label-warning');
							t.addClass('label-success');
						}
						html = t.html();
						t.html(t.attr('data-after-ajax'));
						t.attr('data-after-ajax', html);
					}
				});
			}
		}
	});


	$('form.ajax-submit').live('submit', function(e) {
		var t = $(this);
		t.css({opacity:0.5});
		var sm = t.find('input[type="submit"]').attr('disabled','disabled').addClass('disabled');
		ajaxload_loading.show();
		$.ajax(t.attr('data-ajax-to') || t.attr('action'), {
			type    : 'post',
			data	: t.serialize() + '&t=' + new Date().getTime(),
			success : function(r) {
				t.replaceWith(r);
				t.css({opacity:1});
				ajaxload_loading.hide();
				sm.removeAttr('disabled').removeClass('disabled');
			}
		});

		return false;
	});
	
	
	// DELETE BUTTON
	$('input[name="act_delete"]').live('click', function(e) {
		var t = $(this);
        msg = t.attr('data-must-confirm-msg');
        msg = msg || 'Are you sure want to continue?';
        if(!confirm(msg)) {
            e.preventDefault();
            return false;
        }
        
		$('form').attr('action', t.attr('data-action') ? t.attr('data-action') : 'delete');
		
		$('form').submit();
	});

	// VIEW HELPER
		// Render select box
		function renderSelectbox(d) {
			x = [];
			for(var k in d) {
				x.push('<option value="');
				x.push(k);
				x.push('">');
				x.push(d[k]);
				x.push('</option>');
			}
			return x.join('');
		}

	// Currency rate
	var currencyRate = $('.currenry-rate.autoload');

	// Prevent enter-submit
	$(':input').live('keypress', function(e) {
		if(e.which == 13) {
			if(!e.shiftKey) {
			    e.preventDefault();
			}
		}
	});

	// Textarea size
//	var txtareaAttrBlur  = {'rows':1};
//	var txtareaAttrFocus = {'rows':8};
//	$('textarea').attr(txtareaAttrBlur)
//	             .live('focus',function(e){$(this).attr(txtareaAttrFocus)})
//	             .live('blur' ,function(e){$(this).attr(txtareaAttrBlur)});


	$('textarea').attr('rows', 2).attr('cols', 80);

    $('#search-cat').click(function(){
        var srch_cat_list = $('.search-cat-list');
        if(srch_cat_list.css('display') == 'block'){
            srch_cat_list.slideUp(300);
        } else {
            srch_cat_list.slideDown(300);
        }
    });

    // CHECKBOX
    var big_check = $('.check-all'); // Big Checkbox
    var small_check = $('input[name="item_checker[]"]'); // Small Checkbox Items
    var rows_class = 'tr-active'; // BG Rows Class
    big_check.change(function(){
        var status = $(this).attr('checked');
        if(status){small_check.attr('checked',status).parent().parent().addClass(rows_class);} else {small_check.removeAttr('checked').parent().parent().removeClass(rows_class);}
    });

    // CHANGE BG ROWS ACTIVE
    small_check.change(function(){
        if ($(this).attr('checked')) {
            $(this).parent().parent().addClass(rows_class);
        } else {
            big_check.removeAttr('checked');
            $(this).parent().parent().removeClass(rows_class);
        }
    });
    // CHANGE BG ODD FIELD ADD/EDIT FORM
    $('.form-item:even').addClass('tr-even');

    // CHANGE CLASS INPUT IF ERROR
    $('.form-element').has('ul.errors').children('input').addClass('error-input');

    // Tranform title to hint
    $('[title]:not(.no-hint)').each(function(){var t=$(this);t.attr('data-hint-msg',t.attr('title'));t.removeAttr('title');}).addClass('hint');

    // CREATE HINT
    var hint_element = $('.hint:not(input)'); // Class of Elements you wanna push hint
    var hint_temp = '<div class="tooltip fade below in hint-box"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>';
    var plus_height = 0;
    var input_hint = $('input.hint');

    var fnFocus = function(e){
        $('.hint-box').remove();
        t = $(this);
        var pos = t.position();
        var offset = t.offset();
        var class_name = t.attr('class');
        var inner = t.attr('data-hint-msg');

        // Create Hintbox
        $('body').prepend(hint_temp);
        $('.tooltip-inner').html(inner);
        var hint_box = $('.hint-box');

        // Get Position
        var top = pos.top + t.outerHeight(true) + plus_height;
        var left = offset.left + t.outerWidth(true) / 2 - hint_box.outerWidth(true) / 2 ;

        hint_box.addClass('hint' + class_name).css({'top':top,'left':left}).delay(500).fadeIn(300);
    };
    var fnBlur = function(){
        $('.hint-box').fadeOut(300,function(){$(this).remove()});
    };

    input_hint.live('focus', fnFocus).live('blur' , fnBlur);
    hint_element.live('mouseenter', fnFocus).live('mouseleave', fnBlur);

    setTimeout(function(){ $('.shout-box').fadeOut()}, 10000);

    $('form').live('submit',function(e){ajaxload_loading.show()});
    
});